package cn.sccl.common.scheduler;

import cn.sccl.common.scheduler.model.TaskFireLog;
import cn.sccl.common.scheduler.model.TaskScheduled;
import cn.sccl.common.scheduler.service.TaskFireLogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author _minus
 * @create 2017-10-04 14:18
 */
@Service
public class SchedulerService implements ApplicationContextAware {

	@Autowired
	private TaskFireLogManager taskFireLogManager ;

	// @Autowired
	private SchedulerManager schedulerManager;

	protected ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	// 获取所有作业
	public List<TaskScheduled>
	getAllTaskDetail() {
		return schedulerManager.getAllJobDetail();
	}

	/**
	 * 执行作业
	 * 必要参数 task_name 和taskGroup
	 * @param taskScheduled
	 */
	public void execTask(TaskScheduled taskScheduled) {
		schedulerManager.runJob(taskScheduled);
	}


	/**
	 * 执行作业
	 * 必要参数 task_name 和taskGroup
	 * @param taskScheduled
	 */
	// 恢复作业
	public void resumeJob(TaskScheduled taskScheduled) {
		schedulerManager.resumeJob(taskScheduled);
	}

	/**
	 * 暂停作业
	 * 必要参数 task_name 和taskGroup
	 * @param taskScheduled
	 */
	//
	public void pauseJob(TaskScheduled taskScheduled) {
		schedulerManager.stopJob(taskScheduled);
	}

	// 删除作业

	/**
	 * 必要参数 task_name 和taskGroup
	 * @param taskScheduled
     */
	public void delTask(TaskScheduled taskScheduled) {
		schedulerManager.delJob(taskScheduled);
	}

	// 修改任务
	public void updateTask(TaskScheduled taskScheduled) {
		Assert.notNull(taskScheduled.getJobType(), "JOBTYPE");
		Assert.notNull(taskScheduled.getTaskType(), "TASKTYPE");
		Assert.notNull(taskScheduled.getTargetObject(), "TARGETOBJECT");
		Assert.notNull(taskScheduled.getTargetMethod(), "TARGETMETHOD");
		Assert.notNull(taskScheduled.getTaskCron(), "TASKCRON");
		Assert.notNull(taskScheduled.getTaskDesc(), "TASKDESC");
		schedulerManager.updateTask(taskScheduled);
	}
	/**
	 *
	 * @param taskScheduled
	 * @return
     */
	public boolean isExist(TaskScheduled taskScheduled) {
		return schedulerManager.isExist(taskScheduled) ;
	}

	public TaskFireLog getFireLogById(String id) {
		return taskFireLogManager.get(id);
	}

	public TaskFireLog updateLog(TaskFireLog record) {
		taskFireLogManager.save(record);
		taskFireLogManager.get(record.getId()) ;
		return record;
	}

	public TaskScheduled getJobDetail(TaskScheduled taskScheduled) {

		return schedulerManager.getJobDetail(taskScheduled);
	}
}
